package com.seventeen.monster.redisson.support;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * @author seventeen
 */
public class CustomExpressionParser {
    private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

    public static Object getValueByExpression(Map<String, Object> variables, String expressionString) {
        EvaluationContext evaluationContext = new StandardEvaluationContext(variables.remove("root"));
        variables.forEach(evaluationContext::setVariable);
        Expression expression = EXPRESSION_PARSER.parseExpression(expressionString, new TemplateParserContext());
        return expression.getValue(evaluationContext, Object.class);
    }
}